<template>
  <div>
    <el-card>
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleSearch" type="primary" :icon="Search">查询</el-button>
          <el-button @click="username = ''; handleSearch()" type="default">清空</el-button>
        </el-form-item>
      </el-form>
      <el-button @click="handleAddUser" type="primary">添加</el-button>
      <el-button @click="handleBatchDeleteUser" :disabled="!selects.length" type="danger">批量删除</el-button>
      <el-table @select="handleSelect" @select-all="handleSelect" v-loading="loading" :data="userList" border
        style="margin-top: 20px">
        <el-table-column type="selection" width="80"></el-table-column>
        <el-table-column type="index" label="序号" width="80"> </el-table-column>
        <el-table-column prop="username" label="用户名"></el-table-column>
        <el-table-column prop="nickName" label="用户昵称"></el-table-column>
        <el-table-column prop="roleName" label="权限列表"></el-table-column>
        <el-table-column prop="gmtCreate" label="创建时间"></el-table-column>
        <el-table-column prop="gmtModified" label="更新时间"></el-table-column>
        <el-table-column v-slot="{ row }" label="操作" width="180" fixed="right">
          <el-tooltip class="box-item" effect="dark" content="分配角色" placement="top">
            <el-button @click="handleAssignRole(row)" type="info" :icon="UserFilled" size="small"></el-button>
          </el-tooltip>
          <el-tooltip class="box-item" effect="dark" content="修改用户" placement="top">
            <el-button @click="handleEdit(row)" type="primary" :icon="EditPen" size="small"></el-button>
          </el-tooltip>
          <el-tooltip class="box-item" effect="dark" content="删除用户" placement="top">
            <el-button @click="handleDelete(row)" type="danger" :icon="Delete" size="small"></el-button>
          </el-tooltip>
        </el-table-column>
      </el-table>
      <el-pagination v-model:current-page="page" v-model:page-size="limit" :page-sizes="[3, 5, 10, 20, 50]"
        layout="prev, pager, next, jumper, ->, sizes, total, " :total="total" style="margin-top: 15px"
        @size-change="handleSizeChange" @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>

    <!-- 添加用户 -->
    <el-dialog v-model="addUserDialogVisible" :title="userInfo.id ? '修改用户' : '添加用户'" width="50%">
      <el-form label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="userInfo.username" placeholder="用户名"></el-input>
        </el-form-item>
        <el-form-item label="用户昵称">
          <el-input v-model="userInfo.nickName" placeholder="用户昵称"></el-input>
        </el-form-item>
        <el-form-item v-if="!userInfo.id" label="用户密码">
          <el-input v-model="userInfo.password" type="password" placeholder="用户密码"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addUserDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddOrUpdate">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 分配角色 -->
    <el-dialog v-model="assignRoleDialogVisible" title="设置角色" width="50%">
      <el-form label-width="85px">
        <el-form-item label="用户名">
          <el-input :value="user.username" :disabled="true"></el-input>
        </el-form-item>
        <!-- 角色列表 -->
        <el-form-item label="角色列表">
          <el-checkbox v-model="checkAll" :indeterminate="isIndeterminate"
            @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="checkedRoles" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="(role, index) in roles" :key="index" :label="role">
              {{ role.split(':')[1] }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignRoleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAssignRole">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import { Search, UserFilled, EditPen, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { reqAddUser, reqBatchDeleteUser, reqDeleteUser, reqDoAssign, reqGetUserList, reqToAssign, reqUpdateUser } from '@/api/acl/user'
const userList = ref([])
const limit = ref(5)
const page = ref(1)
const total = ref(20)
// 每页显示条数改变
const handleSizeChange = (val: number) => {
  limit.value = val
  getUserList()
}
// 页码改变
const handleCurrentChange = (val: number) => {
  page.value = val
  getUserList()
}

// 获取用户列表
const loading = ref(false)
const username = ref('')
const getUserList = async () => {
  loading.value = true
  const res = await reqGetUserList(page.value, limit.value, username.value)
  userList.value = res.items
  total.value = res.total
  loading.value = false
}
onMounted(() => {
  getUserList()
})

// 根据用户名搜索
const handleSearch = () => {
  getUserList()
}

// 添加用户
//#region 
const userInfo = reactive({
  username: '',
  nickName: '',
  password: ''
})
const addUserDialogVisible = ref(false)
const handleAddUser = () => {
  // 初始化
  delete userInfo.id
  Object.assign(userInfo, {
    username: '',
    nickName: '',
    password: ''
  })
  addUserDialogVisible.value = true
}
// 提交添加请求
const submitAddOrUpdate = async () => {
  if (userInfo.id) {
    await reqUpdateUser(userInfo)
    ElMessage.success('修改用户成功！')
  } else {
    await reqAddUser(userInfo)
    ElMessage.success('添加用户成功！')
  }
  getUserList()
  addUserDialogVisible.value = false
}
//#endregion

/**
 * 修改用户
*/
//#region
const handleEdit = (row) => {
  Object.assign(userInfo, row)
  addUserDialogVisible.value = true
}
// 删除用户
const handleDelete = async (row) => {
  await reqDeleteUser(row.id)
  ElMessage.success('删除用户成功！')
  getUserList()
}
//#endregion

/**
 * 批量删除用户
 */
//#region
// 选中用户
const selects = ref([])
const handleSelect = (selection, row) => {
  selects.value = selection
}
// 批量删除
const handleBatchDeleteUser = async () => {
  const idList = selects.value.map(item => item.id)
  console.log(idList)
  await reqBatchDeleteUser(idList)
  getUserList()
}
//#endregion

/**
 * 分配角色
 */
const checkAll = ref(false)
const isIndeterminate = ref(true)
const checkedRoles = ref([])
const roles = ref([])
const handleCheckAllChange = (val: boolean) => {
  checkedRoles.value = val ? roles.value : []
  isIndeterminate.value = false
}
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === roles.value.length
  isIndeterminate.value = checkedCount > 0 && checkedCount < roles.value.length
}

const user = reactive({})
const assignRoleDialogVisible = ref(false)
const handleAssignRole = async (row) => {
  Object.assign(user, row)

  const res = await reqToAssign(row.id)
  roles.value = res.allRolesList.map(item => `${item.id}:${item.roleName}`)
  checkedRoles.value = res.assignRoles.map(item => `${item.id}:${item.roleName}`)

  // 处理半选
  // if (checkedRoles.value.length && checkedRoles.value.length < roles.value.length ){
  //   isIndeterminate.value = true
  // } else {
  //   isIndeterminate.value = false
  // }
  isIndeterminate.value = !!checkedRoles.value.length && checkedRoles.value.length < roles.value.length

  assignRoleDialogVisible.value = true


}
// 提交分配角色
const submitAssignRole = async () => {
  const roleId = checkedRoles.value.map(item => item.split(':')[0]).join()
  await reqDoAssign(user.id, roleId)
  getUserList()
  ElMessage.success('分配角色成功！')
  assignRoleDialogVisible.value = false
}

</script>

<style scoped>

</style>